package com.putao.album.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.putao.album.util.StringHelper;
import com.putao.album.util.ViewHelper;
import com.umeng.analytics.MobclickAgent;

public abstract class BaseActivity extends FragmentActivity implements OnClickListener, IActivityInterface {
    public Context mContext;
    public Activity mActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
        doBefore();
        View containerView = getLayoutInflater().inflate(doGetContentViewId(), null);
        setContentView(containerView);
        doInitSubViews(containerView);
        doInitData();
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private void init() {
        mActivity = this;
        mContext = this;
    }


    protected <T extends View> T queryViewById(int viewId) {
        return ViewHelper.queryViewById(mActivity, viewId);
    }

    public static <T extends View> T queryViewById(View parent, int viewId) {
        return ViewHelper.queryViewById(parent, viewId);
    }


    /**
     * 查找View并且添加点击事件监听
     *
     * @param viewId
     * @param clicklistener
     * @param <T>
     * @return
     */
    protected <T extends View> T queryViewById(int viewId, boolean clicklistener) {
        if (viewId > 0) {
            T view = (T) findViewById(viewId);
            if (clicklistener && view != null)
                addOnClickListener(view);
            return view;
        }
        return null;
    }


    /**
     * set OnClickListener for every View
     *
     * @param views
     */
    protected void addOnClickListener(View... views) {
        OnClickListener listener = (OnClickListener) mActivity;
        if (listener != null)
            for (int i = 0; i < views.length; i++)
                views[i].setOnClickListener(listener);
    }

    /**
     * 根据资源Id设置当前资源ID对应的View点击事件监听
     *
     * @param resIds
     */
    protected void addOnClickListener(int... resIds) {
        OnClickListener listener = (OnClickListener) mActivity;
        if (listener != null) {
            for (int i = 0; i < resIds.length; i++) {
                queryViewById(resIds[i], true);
            }
        }
    }

    public void doBefore() {
    }

    public void showToast(String message) {
        if (!StringHelper.isEmpty(message))
            Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
    }

}
